// 导入模块 Import modules
import { StorageManager } from './manager';
import type { PlayerDataInterface } from './interface/player';
import { StorageTypes } from './enum/manager';
import { VirtualPlayerDataInterface } from './data/player';

/**
 * @zh 玩家数据空间管理类
 * @en Class for player data space management
 * @author Lusisi卢喜喜 <3986410685@qq.com>
 */
class PlayerStorageManager extends StorageManager<PlayerDataInterface> {
    /**
     * @zh 构造函数
     * @param storageKey 存储空间键名
     * @param storageType 存储空间类型
     * @en Public constructor
     * @param storageKey Storage space key name
     * @param storageType Whether it's a group storage space
     */
    public constructor(
        storageKey: 'player',
        storageType: StorageTypes.Group = StorageTypes.Group
    ) {
        super(storageKey, storageType);
    }

    /**
     * @zh 排名
     * @param callback 回调玩家数据的函数
     * @param count 排名个数
     * @returns 排名列表
     * @example
     * import { PlayerStorage } from "@/storage/storage";
     * // 获取等级（level）排前50名的玩家
     * // 如果数据库里的数据个数不足50个，则按照顺序有多少就返回多少
     * let list = PlayerStorage.rank((data) => data.level, 50); // 返回排好序的数据列表
     * @en Rank
     * @param callback Function of callback player data
     * @param count Count of ranking
     * @returns rank list
     * @example
     * import { PlayerStorage } from "@/storage/storage";
     * // Get the top 50 players in level ranking
     * // If the number of data in storage is less than 50, return as many as there are in order
     * let list = PlayerStorage.rank((data) => data.level, 50); // Return a sorted list of data
     */
    public async rank(
        callback: (
            /**
             * @zh 玩家数据接口
             * @en Player data interface
             */
            data: PlayerDataInterface
        ) => number,
        count: number
    ): Promise<ReturnValue<PlayerDataInterface>[]> {
        // 获取排名对象 Get ranking object
        const dataInterface = VirtualPlayerDataInterface;
        const value = callback(dataInterface);
        let key: keyof PlayerDataInterface;
        let name: keyof PlayerDataInterface | undefined;
        for (key in dataInterface) {
            if (dataInterface[key] === value) {
                name = key;
            }
        }
        if (name === undefined) {
            throw Error(
                '传入的number对象必须根据回调的data参数进行选择。 ' +
                    'The number object passed in must be selected based on `data` of callback.'
            );
        }
        // 获取数据并进行排名 Get data and rank them
        const data = await this.getDataList();
        const sortData = data.sort(
            (a, b) => (b?.value[name] as number) - (a?.value[name] as number)
        );
        return sortData.slice(0, count);
    }
}

// 导出模块 Export modules
export { PlayerStorageManager };
